<!--工序标识卡打印-->
<template>
  <basic-container>
    <div class="processCardPrint-container">
      <div class="form">
        <avue-form :key="timer" ref="form" v-model="form" :option="option" @submit="submit">
          <template slot-scope="{}" slot="mpqLabel">
            <el-tooltip class="item" effect="dark" content="MPQ（Minimum Package Quantity）指物料最小包装数量" placement="top-start">
              <i class="el-icon-info"></i>
            </el-tooltip>
            <span>&nbsp;MPQ:</span>
          </template>
        </avue-form>
      </div>
    </div>
    <global-modal-template :visibile.sync="visibile" :option="tableOption" @getSelectedRows="getSelectedRows" :key="timer" @newKey="newKey"> </global-modal-template>
  </basic-container>
</template>
<script>
import GlobalModalTemplate from '@/components/common-modal-template/global-modal-template.vue';
import { getList as getProductionOrderNoList } from '@/api/product/productionorder';
import { getList as getPartnerList } from '@/api/admin/partner';
import { getWorkorderRoute } from '@/api/product/workorder';
import { print } from '@/api/product/processCardPrint';

export default {
  name: 'processCardPrint',
  components: {
    GlobalModalTemplate
  },
  mounted() {},
  data() {
    return {
      modalName: '', //打开公用模态框名称
      visibile: false,
      form: {},
      tableOption: {},
      timer: new Date().getTime(),
      option: {
        submitText: '打印',
        labelWidth: 130,
        menuSpan: 14,
        column: [
          {
            type: 'search',
            label: '工单号',
            prop: 'workOrderNo',
            disabled: true,
            rules: [
              {
                required: true,
                trigger: 'submit',
                validator: (rule, value, callback) => {
                  callback();
                }
              }
            ],
            appendClick: () => {
              this.openUserCommonModal({ type: 'workOrderNo' });
            }
          },
          {
            label: '产品编码',
            prop: 'partNo',
            disabled: true
          },
          {
            label: '产品名称',
            prop: 'partName',
            disabled: true
          },
          {
            label: '产品型号',
            prop: 'partModel',
            disabled: true
          },
          {
            label: '订单号',
            prop: 'productionOrderNo',
            disabled: true
          },
          {
            label: '客户编码',
            prop: 'partnerCode',
            disabled: true
          },
          {
            label: '客户名称',
            prop: 'name',
            disabled: true
          },
          {
            label: '工单计划数量',
            prop: 'planQuantity',
            disabled: true
          },
          {
            label: '工序',
            type: 'select',
            prop: 'process',
            dicData: [],
            rules: [
              {
                required: true,
                message: '请选择工序',
                trigger: 'change'
              }
            ]
          },
          {
            label: '工序产出数量',
            prop: 'outputQuantity',
            value: 0,
            minRows: 0,
            precision: 0,
            type: 'number',
            rules: [
              {
                required: true,
                message: '请填写工序产出数量',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '打印机',
            prop: 'printName',
            type: 'search',
            disabled: true,
            rules: [
              {
                required: true,
                message: '请选择打印机',
                trigger: 'blur'
              }
            ],
            appendClick: () => {
              this.openUserCommonModal({ type: 'printId' });
            }
          },
          {
            type: 'search',
            label: '标签模板',
            prop: 'labelTemplateName',
            disabled: true,
            rules: [
              {
                required: true,
                message: '请选择模板标签',
                trigger: 'blur'
              }
            ],
            appendClick: () => {
              this.openUserCommonModal({ type: 'labelTemplateName' });
            }
          }
        ]
      }
    };
  },
  methods: {
    formatterDate() {
      let date = new Date();
      let year = date.getFullYear();
      let month = date.getMonth() + 1;
      let day = date.getDate();
      month = month > 9 ? month : '0' + month;
      day = day < 10 ? '0' + day : day;
      return year + month + day;
    },
    submit() {
      this.$refs.form.validate((valid, done) => {
        if (valid) {
          let params = {
            partId: this.form.partId,
            partnerCode: this.form.partnerCode,
            partnerId: this.form.partnerId,
            printId: this.form.printId,
            labelTemplateId: this.form.labelTemplateId,
            extFields: JSON.stringify({
              output_quantity: this.form.outputQuantity,
              workorderno: this.form.workOrderNo,
              planQuantity: this.form.planQuantity,
              routeName: this.form.$process,
              productionOrderNo: this.form.productionOrderNo,
              printdate: this.formatterDate()
            })
          };
          console.log('params', params);
          print(params).then(
            () => {
              this.$message({
                type: 'success',
                message: '操作成功!'
              });
              done();
              this.$refs.form.resetForm();
            },
            (error) => {
              done();
              window.console.log(error);
            }
          );
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    getSelectedRows(rowData) {
      let processIndex = this.option.column.findIndex((col) => col.prop == 'process');

      switch (this.modalName) {
        case 'productionOrderNoModal':
          this.option.column[processIndex].dicData = [];
          this.form.process = '';
          this.form.printId = '';
          this.form.printName = '';
          this.form.labelTemplateId = '';
          this.form.labelTemplateName = '';
          this.form.outputQuantity = 0;

          this.form.partId = this._get(rowData, 'partMasterId', ''); // 物料id
          this.form.workOrderNo = this._get(rowData, 'orderNo', '');
          this.form.partNo = this._get(rowData, 'partNo', '');
          this.form.partName = this._get(rowData, 'partName', '');
          this.form.partModel = this._get(rowData, 'partModel', '');
          this.form.productionOrderNo = this._get(rowData, 'salesOrderNo', '');
          this.form.planQuantity = this._get(rowData, 'planQuantity', '');
          this.form.partnerCode = this._get(rowData, 'partnerCode', '');
          this.form.name = this._get(rowData, 'partnerName', '');
          this.form.partnerId = this._get(rowData, 'partnerId', '');
          // 根据工单号查询所有过站工序工序
          getWorkorderRoute(this.form.workOrderNo)
            .then((res) => {
              let data = res.data.data;
              this.option.column[processIndex].dicData = data
                .filter((d) => d.isStation)
                .map((d) => {
                  return {
                    label: d.name,
                    value: d.id
                  };
                });
            })
            .catch((err) => {});
          this.visibile = false;
          break;

        case 'printersNameModal':
          this.form.printId = this._get(rowData, 'id', '');
          this.form.printName = this._get(rowData, 'name', '');
          this.visibile = false;
          break;
        case 'labelTemplateNameModal':
          this.form.labelTemplateId = this._get(rowData, 'id', '');
          this.form.labelTemplateName = this._get(rowData, 'fileName', '');
          this.visibile = false;
          break;
        default:
          break;
      }
    },
    openUserCommonModal(params) {
      let { type } = params;
      switch (type) {
        // 工单号
        case 'workOrderNo':
          this.modalName = 'productionOrderNoModal';
          this.visibile = true;
          this.tableOption = {
            modalTitle: '选择工单号（双击进行选择）',
            url: '/api/mes-product/work-order/page',
            isPage: true,
            query: {
              status: 3
            },
            rowSelectionType: 'single',
            menu: false,
            editBtn: false,
            menuWidth: 100,
            searchLabelWidth: 90,
            templateName: 'WORKORDER'
          };
          break;
        // 打印机
        case 'printId':
          this.modalName = 'printersNameModal';
          this.visibile = true;
          this.tableOption = {
            modalTitle: '选择打印机（双击进行选择）',
            url: '/api/mes-product/ems-equipment/page?type=PRINTER',
            isPage: true,
            rowSelectionType: 'single',
            menu: false,
            editBtn: false,
            menuWidth: 100,
            searchLabelWidth: 90,
            templateName: 'PRINTER'
          };
          break;
        // 标签模板
        case 'labelTemplateName':
          this.modalName = 'labelTemplateNameModal';
          this.visibile = true;
          this.tableOption = {
            modalTitle: '选择标签模版（双击进行选择）',
            url: `/api/mes-admin/labeltemplate/page?type=manufacturing_process&subType=flow_card&status=1`,
            isPage: true,
            rowSelectionType: 'single',
            menu: false,
            editBtn: false,
            menuWidth: 100,
            searchLabelWidth: 90,
            templateName: 'LABELTEMPLATE'
          };
        default:
          break;
      }
    },
    newKey() {
      this.timer = new Date().getTime();
    }
  }
};
</script>

<style lang="scss" scoped>
.processCardPrint-container {
  height: 83vh;
}
.form {
  width: 70%;
  display: flex;
  flex-direction: column;
  margin-left: 25%;
  ::v-deep .avue-form__group--flex {
    flex-direction: column;
  }
}
</style>
